var mongoose=require('mongoose');
var config=require('../config');
var mongodb = require('mongodb');
var Schema=mongoose.Schema;
var Category=require('./category');
var db=mongoose.createConnection(config.db_url);
db.on('error',function(error){
    db.close();
    console.log(error);
});

db.on('close', function () {
    db.open(config.db_url);
    console.log("重新连接mongo");
});

db.model('Category',Category.categorySchema);
var goodsSchema = new Schema({
    sort:String,
    name:String,
    attr:String,
    price:Number,
    imgData:String,
    category:{type:Schema.Types.ObjectId,ref:'Category'},
    sellNum:{type:Number,default:0},
    createDate:{type:Date,default:Date.now}
});
var Goods = db.model("Goods", goodsSchema);

Goods.prototype.findAll=function(callback){
    Goods.find({},function(err,datas){
        callback(datas)
    })

}
Goods.prototype.findByCategoryId=function(id,callback){
    Goods.find({category:id},function(err,datas){
        callback(datas)
    })

}
Goods.prototype.findByGoodsById=function(id,callback){
    Goods.findOne({_id:id},function(err,data){
        callback(data)
    })

}

Goods.prototype.delById=function(id,callback){
    Goods.remove({_id:id},function(err){
        callback(err)
    })

}
Goods.prototype.updById=function(id,opt,callback){
    Goods.update({_id:id},opt,function(err){
        callback(err)
    })

}
Goods.prototype.findForPage=function(obj,callback){
    var q=obj.search||{};                                       //查询条件
    var col=obj.columns||{};                                    //返回字段
    var query=Goods.find(q,col).skip(obj.page.skipFrom).limit(obj.page.limit);

    query.exec(function(err, datas) {
        if (err) {
            callback(err, null, null);
        } else {
            Goods.count(q, function(err, count) {
                if (err) {
                    callback(err, null, null);
                } else {
                    var pageCount = Math.ceil(count / obj.page.limit);
                    callback(null,count,pageCount, datas);
                }
            });
        }
    });
}

module.exports = Goods;
module.exports.goodsSchema = goodsSchema;